/**
 * Created by pkd on 2017/3/13.
 */

var bgTask = module.exports;
bgTask.jobTimerId;
bgTask.lastExpireGoodsDay = 0;
bgTask.isRunning = false;
bgTask.lastGatherTimeHDK = 0;
bgTask.lastGatherTimeDTK = 0;
bgTask.nextPageHDK = 1;
bgTask.nextPageDTK = 1;
bgTask.gatherIntervalHDK = 10 * 60 * 1000;
bgTask.gatherIntervalDTK = 60 * 60 * 1000;
bgTask.onDoingGoodList = [];
bgTask.onDoingGoodListAli = null;
bgTask.timeSetSellerIdIfNull = 0;
bgTask.maxGoodsKeyDTK = 0;

// 2小时销售额（价格*数量）大于多少算热推
var biz2hour4hot = 180;
var packSizeSetNullSellerId = 40;       // 每次更新多少个无sellerId的商品，不可大于40个。
var timeCheckNullSellerId = 60000;      // 多久检查无sellerId的商品，建议60秒。
var checkGoodsInterval = 700;

var mysql = require('mysql');
var aliApiHelper = require('./util/aliApiHelper');
var goodsDao = require('./dao/goods.js');
var updateGoodsDao = require('./dao/update_goods.js');
var hidCouDao = require('./dao/hidden_coupons.js');
var paymentDao = require('./dao/payment.js');
var request = require('request');
var commonUtil = require('./util/common');
var CMS = require('./dao/cms');
var CONFIG = require('./config/config_local');
var spiderGoodsDao = require('./dao/spider_goods');
var boutiquePoolDao = require('./dao/boutique_pool');
var flashSaleDao = require('./dao/flash_sale');

var tag4fqcat = ['全部', '女装', '男装', '内衣', '美妆', '配饰', '鞋品', '箱包', '儿童', '母婴', '居家', '美食', '数码', '家电', '其他', '文体', '车品'];
var tag4cid =   ['全部', '女装', '母婴', '美妆', '居家', '鞋包服饰', '美食', '文体车品', '数码家电', '男装', '内衣', '其他'];
var cid2fqcat = {0:0,     1:1,    2:9,    3:4,    4:10,   5:14,       6:11,   7:14,       8:12,       9:2,    10:3,   11:14};

function doNothing() {
    
}
//从阿里获取商品的信息
function getGoodsInfoFromAlimama(goodsList, cb) {
    var auctionIds = [];
    var result = {};
    goodsList.forEach(function (g) {
        auctionIds.push(g.auctionId);
        result[g.auctionId] = {dbDat:g};
    })
    aliApiHelper.getGoodsInfoSimple(auctionIds, function (err, rspAli) {
        if(err){
            cb(err);
            return;
        }
        if(rspAli == '' || rspAli == undefined) {
            console.log(rspAli);
            cb(false);
            return;
        }
        rspAli.forEach(function (g) {
            g.avail = 1;
            var dat = result[g.num_iid];
            if(dat) dat.aliDat = g;
        });
        cb(null, result);
    });
}

/**
 * 客户端辅助刷新券信息
 * @param  auctionIdList
 *         url/goods/getGoodsOfAuctionIdList
 */

function requestToPD(pdId, reason) {
    console.log(pdId);
    console.log(reason);
    var param = {};
    param.app_time = new Date().getTime();
    param.app_key = 'blpd';
    param.status_reason = reason;
    param.ids = JSON.stringify(pdId);
    param.app_sign = commonUtil.getAppSign (param.app_key, CONFIG.APP_secret, param.app_time);

    commonUtil.baseRequest(CONFIG.PaoDanHost, 'serverGood/offGoodsByBenliu', param, function(err, data){
        if(err) {
            console.log(err);
        } else {
            console.log(data);
        }
    })
}

function gatherGoodsDTK() {
    request({url:'http://api.dataoke.com/index.php?r=Port/index&type=total&appkey=169foxqf9m&v=2&page=' + bgTask.nextPageDTK}, function (error, response, body) {

        if(error || response.statusCode != 200 || !body){
            console.log('大淘客获取失败！');
            return;
        }
        try{
            var rsp = JSON.parse(body);
            if(!rsp || !rsp.data ||!rsp.result){
                console.log('大淘客获取失败！');
                return;
            }
            var result = rsp.result;
            var goods = [];
            var auctionIds = [];
            var minGoodsKeyDTK = 999999999;
            var maxGoodsKeyDTK = 0;
            result.forEach(function (g, i) {
                auctionIds.push(g.GoodsID);
                if(maxGoodsKeyDTK < g.ID) maxGoodsKeyDTK = g.ID;
                if(minGoodsKeyDTK > g.ID) minGoodsKeyDTK = g.ID;
                var good = {
                    source:'大淘客',
                    auctionId:g.GoodsID,
                    pictUrl:g.Pic,
                    title:g.Title,
                    reservePrice:g.Org_Price,
                    zkPrice:g.Org_Price,
                    biz30day:g.Sales_num,
                    sellerId:g.SellerID,
                    adTitle:g.Introduce,
                    userType:g.IsTmall,
                    isTMall:g.IsTmall,
                    hiddenAmount:g.Quan_price,
                    hiddenActivityId:g.Quan_id,
                    hiddenEndTime:g.Quan_time,
                    hiddenLeftCount:g.Quan_surplus,
                    hiddenTotalCount:g.Quan_receive + g.Quan_receive,
                    goodShortTitle:g.D_title,
                    includeDxjh:1,
                    extActivityId:g.Quan_id
                };

                if(isNaN(g.Quan_condition)){
                    good.hiddenInfo = g.Quan_condition;
                }
                else{
                    good.hiddenStartFee = parseFloat(g.Quan_condition);
                }
                good.fqCat = cid2fqcat[g.Cid];
                good.tag = tag4cid[g.Cid];
                var commJihua = parseFloat(g.Commission_jihua);
                var commQQHD = parseFloat(g.Commission_queqiao);
                if(commJihua >= commQQHD){
                    good.realTkRate = commJihua;
                    good.tkRate = 0;
                    good.eventRate = 0;
                    good.maxTkRate = good.realTkRate;
                    good.tkType = '定向';
                }
                else{
                    good.realTkRate = commQQHD;
                    good.tkRate = 0;
                    good.maxTkRate = 0;
                    good.eventRate = good.realTkRate;
                    good.tkType = '鹊桥';
                }
                var realPrice = g.Price;
                good.tkCommFee = realPrice * good.realTkRate / 100;
                if(!good.activityType || good.activityType == '普通活动'){
                    good.activityType = '宝贝精选';
                }
                if(g.planlink){
                    good.planlink = commonUtil.GetQueryString(g.planlink, 'me');
                }
                if(good.realTkRate >= 35 && good.tkCommFee > 8){
                    good.isHighCoupon = 1;
                }else{
                    good.isHighCoupon = 0;
                }
                var realPrice = g.Price;
                if(realPrice < 10) good.isCheap = 1; else good.isCheap = 0;
                if(realPrice <= good.hiddenAmount) good.isHighScore = 1; else good.isHighScore = 0;

                if( (parseFloat(good.zkPrice) - parseFloat(good.hiddenAmount)) > 0 ) {
                    goods.push(good);
                }

            });
            var arr = {};
            arr.auctionIdList = auctionIds;
            goodsDao.isExist(arr, function(err, data) {
                if(err) {
                    console.log('采集大淘客后，检查重复商品失败！');
                    return;
                }
                if(data.length < 30 && data.length < auctionIds.length / 3 && bgTask.nextPageDTK < 200 && minGoodsKeyDTK > bgTask.maxGoodsKeyDTK){
                    bgTask.lastGatherTimeDTK = (new Date()).getTime() + 10000 ;
                    ++bgTask.nextPageDTK;
                }
                else{
                    bgTask.maxGoodsKeyDTK = maxGoodsKeyDTK;
                    bgTask.nextPageDTK = 1;
                }
                goods = commonUtil.duplicateRemoval(data, goods);
                do{
                    if(goods.length > 40){
                        saveGatherGoods(goods.splice(0, 40), onSaveGoods);
                    }
                    else{
                        saveGatherGoods(goods.splice(0, goods.length), onSaveGoods);
                    }
                }while(goods.length > 0);
            });
        }
        catch (e) {
            console.log(e);
        }
    })
}

function gatherGoodsHDK() {
    request({url:'http://www.haodanku.com/?json=true&api=list&p=' + bgTask.nextPageHDK}, function (error, response, body) {

        if(error || response.statusCode != 200 || !body){
            console.log('好单库获取失败！');
            return;
        }
        try{
            if(!body || body.length < 2 || body.substr(0, 1) != '['){
                console.log('好单库获取失败');
                return;
            }
            var rsp = JSON.parse(body);
            var goods = [];
            var auctionIds = [];
            rsp.forEach(function (g, i) {
                auctionIds.push(g.itemid);
                var good = {
                    source:'好单库',
                    auctionId:g.itemid,
                    pictUrl:g.itempic,
                    shopTitle:g.shopname,
                    title:g.itemtitle,
                    tkCommFee:g.tkmoney,
                    reservePrice:g.itemprice,
                    zkPrice:g.itemprice,
                    biz30day:g.itemsale,
                    fqCat:(g.hasOwnProperty('fqcat')) ? g.fqcat : 14,
                    sellerId:g.userid,
                    tkType:g.tktype,
                    realTkRate:parseFloat(g.tkrates),
                    isBrand:g.is_brand,
                    hiddenAmount:g.couponmoney,
                    couponLeftCount:g.couponsurplus,
                    couponTotalCount:g.couponnum,
                    couponInfo:g.couponexplain,
                    adTitle:g.itemdesc,
                    includeDxjh:1,
                    activityType:g.activity_type,
                };
                if(!good.sellerId){
                    good.sellerId = g.shopid;
                }
                if(!good.shopTitle || good.shopTitle.length < 2){
                    good.shopTitle = g.sellernick;
                }
                if(!good.activityType || good.activityType == '普通活动'){
                    good.activityType = '宝贝精选';
                }
                if(!good.shopTitle || good.shopTitle.length < 2){
                    good.shopTitle = '淘宝/天猫店';
                }
                if(g.couponurl){
                    good.hiddenActivityId = commonUtil.GetQueryString(g.couponurl, 'activityId');
                    if(!good.hiddenActivityId){
                        good.hiddenActivityId = commonUtil.GetQueryString(g.couponurl, 'activity_id');
                    }
                    good.extActivityId = good.hiddenActivityId;
                }
                if(g.planlink){
                    good.planlink = commonUtil.GetQueryString(g.planlink, 'me');
                }
                if(good.realTkRate >= 35 && good.tkCommFee > 8){
                    good.isHighCoupon = 1;
                }else{
                    good.isHighCoupon = 0;
                }
                var realPrice = good.zkPrice - good.hiddenAmount;
                if(g.itemsale2 * realPrice> biz2hour4hot) good.isHot = 1;
                if(realPrice < 10) good.isCheap = 1; else good.isCheap = 0;
                if(realPrice <= good.hiddenAmount) good.isHighScore = 1; else good.isHighScore = 0;
                good.includeDxjh = 1;

                good.tag = tag4fqcat[good.fqCat];
                good.userType = (g.shoptype == ('B')) ? 1 : 0;
                good.tkRate = (good.tkType.indexOf('通用') >= 0) ? good.realTkRate : 0;
                good.maxTkRate = (good.tkType.indexOf('定向') >= 0) ? good.realTkRate : 0;
                good.eventRate = (good.tkType.indexOf('鹊桥') >= 0) ? good.realTkRate : 0;

                if( (good.zkPrice - good.hiddenAmount) > 0 ) {
                    goods.push(good);
                }

                if(g.couponstarttime) {
                    good.hiddenStartTime = commonUtil.formatDate(new Date(parseInt(g.couponstarttime) * 1000));
                }
                if(g.couponendtime) {
                    good.hiddenEndTime = commonUtil.formatDate(new Date(parseInt(g.couponendtime) * 1000));
                }
                if(g.couponexplain) {
                    good.hiddenInfo = g.couponexplain;
                }
                if(g.couponsurplus) {
                    good.hiddenLeftCount = g.couponsurplus;
                }
                if(g.couponnum) {
                    good.hiddenTotalCount = g.couponnum;
                }

            });
            var arr = {};
            arr.auctionIdList = auctionIds;
            goodsDao.isExist(arr, function(err, data) {
                if(err) {
                    console.log('采集商品后，检查重复商品失败！');
                    return;
                }
                if(data.length < 30 && data.length < auctionIds.length / 3 && bgTask.nextPageHDK < 200){
                    bgTask.lastGatherTimeHDK = (new Date()).getTime() + 10000 ;
                    ++bgTask.nextPageHDK;
                }
                else{
                    bgTask.nextPageHDK = 1;
                }
                goods = commonUtil.duplicateRemoval(data, goods );
                do{
                    if(goods.length > 40){
                        saveGatherGoods(goods.splice(0, 40), onSaveGoods);
                    }
                    else{
                        saveGatherGoods(goods.splice(0, goods.length), onSaveGoods);
                    }
                }while(goods.length > 0);
            });
        }
        catch (e) {
            console.log(e);
        }
    })
}

function onSaveGoods(err, result) {
    if(err) console.log(err);
}

function saveGatherGoods(goods, cb) {
    getGoodsInfoFromAlimama(goods, function (err, rspAli) {
        if(err){
            cb('采集商品后，从API取店铺信息：' + err);
            return;
        }
        var goodsAvail = [];
        goods.forEach(function (g) {
            var ali = rspAli[g.auctionId];
            if(!ali || !ali.aliDat) return;
            g.shopTitle = ali.aliDat.nick;
            g.sellerId = ali.aliDat.seller_id;
            goodsAvail.push(g);
        })
        goodsDao.batchCreate(goodsAvail, 0, {source:bgTask.gatherSource}, function (err) {
            if(err){
                cb('采集商品后，添加失败！' );
                return;
            }
            console.log('采集成功！');
            cb(null);
        });
    });
}

function setSellerIdIfNull() {
    var now = (new Date()).getTime();
    if(bgTask.timeSetSellerIdIfNull > now) return;
    bgTask.timeSetSellerIdIfNull = now + timeCheckNullSellerId;

    updateGoodsDao.getAuctionIdsBySellerId(null, packSizeSetNullSellerId, function (err, result) {
        if(err){
            console.log(err);
            return;
        }
        if(result.length >= packSizeSetNullSellerId){
            bgTask.timeSetSellerIdIfNull = now + 500;
        }
        getGoodsInfoFromAlimama(result, function (err1, rspAli) {
            if(err1 || rspAli == ''  || rspAli == undefined) {
                return;
            }
            var sql = 'update goods set shopTitle = case auctionId ';
            var sql2 = 'sellerId = case auctionId ';
            var sql3 = 'where auctionId in (0';
            var sql4 = 'delete from goods where auctionId in (0';
            var param = [];
            var needDel = false;
            for(var ka in rspAli){
                var oa = rspAli[ka];
                if(oa.aliDat){
                    var obj = oa.aliDat;
                    sql += ' when ' + ka + ' then ' + mysql.escape(obj.nick);
                    sql2 += ' when ' + ka + ' then ' + obj.seller_id;
                    sql3 += ',' + ka;

                    // sql += 'update goods set shopTitle = ' + mysql.escape(obj.nick) +
                    //     ', sellerId=' + obj.seller_id + ' where auctionId = ' + ka + '; \n';
                    // param.push([obj.nick]);
                }
                else{
                    sql4 += ',' + ka;
                    needDel = true;
                    // sql += 'delete from goods where auctionId = ' + ka + '; \n';
                }
            }
            sql += ' END, ' + sql2 + ' END ' + sql3 + ');'
            updateGoodsDao.runUpdateSql(sql, param, function (err2, result2) {
                if(err2){
                    console.log(err2);
                }
            })
            if(needDel){
                sql4 += ');';
                updateGoodsDao.runUpdateSql(sql4, [], function (err2, result2) {
                    if(err2){
                        console.log(err2);
                    }
                })
            }
        })
    })
}

function runOnceGatherHDK() {
    var now = (new Date());

    if(now - bgTask.lastGatherTimeHDK > 0){
        bgTask.lastGatherTimeHDK = now.getTime() + bgTask.gatherIntervalHDK;
        gatherGoodsHDK();
        return true;
    }
    return false;
}

function runOnceGatherDTK() {
    var now = (new Date());

    if(now - bgTask.lastGatherTimeDTK > 0){
        bgTask.lastGatherTimeDTK = now.getTime() + bgTask.gatherIntervalDTK;
        gatherGoodsDTK();
        return true;
    }
    return false;
}

function runOnceExpire () {
    if(bgTask.goodsIdFinishProcess == 0) {
        var now = new Date();
        var dayIndex = now.getYear() * 400 + now.getMonth() * 31 + now.getDate();
        if(bgTask.lastExpireGoodsDay != dayIndex){
            spiderGoodsDao.spiderActivityType({type:'聚划算', page: 1});
            spiderGoodsDao.spiderActivityType({type:'淘抢购', page: 1});
            bgTask.lastExpireGoodsDay = dayIndex;
            var expiredInfo = {};
            expiredInfo.maxDay = 30;
            updateGoodsDao.expiredPdGoods(expiredInfo, function(e, d){
                if(e) {
                    console.log(e);
                } else {
                    if(d.length > 0) {
                        requestToPD(d, '商品过期下架,系统自动下架！');
                    }
                    updateGoodsDao.expired(expiredInfo, function(err, data) {
                        if(err) {
                            console.log(err);
                        } else {
                            console.log(data);
                        }
                    });
                }
            });

            goodsDao.expiredAuditGoods( function(e, d) {
                if(e) {
                    console.log(e);
                } else {
                    console.log(d);
                }
            });

            paymentDao.expiredOrders( function(e, d){
                if(e) {
                    console.log(e);
                } else {
                    console.log(d);
                }
            });

            CMS.expiredCMSStatus(function (e, d){
                if(e) {
                    console.log(e);
                } else {
                    console.log(d);
                }
            });
            // spiderGoodsDao.spiderDtkGoods();
            // boutiquePoolDao.sysGatherEveryDay(doNothing);
            // spiderGoodsDao.spiderDtkGoods();
            // spiderGoodsDao.spiderHdkGoods();
            // spiderGoodsDao.spiderMtkGoods();
            // spiderGoodsDao.spiderTkjdGoods();
            // spiderGoodsDao.spiderYsdGoods();
            // spiderGoodsDao.spiderQtkGoods();
        }
        var gatherTime = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
        if(gatherTime.indexOf('8:20:0') >= 0 || gatherTime.indexOf('23:50:0') >= 0 || gatherTime.indexOf('15:50:0') >= 0 || gatherTime.indexOf('11:20:0') >= 0 ) {
            spiderGoodsDao.spiderDtkGoods();
            boutiquePoolDao.sysGatherEveryDay(doNothing);
            boutiquePoolDao.delExpiredGoods(doNothing);
        }
        var spiderTime = ['17:5:0', '19:5:0', '20:5:0','21:5:0','0:5:0','8:5:0','10:5:0','13:5:0','15:5:0'];
        if(spiderTime.indexOf(gatherTime) >= 0 ) {
            flashSaleDao.spiderAuctionId(doNothing);
        }
        if(now.getMinutes() % 10 == 0) {
            spiderGoodsDao.spiderDtkGoods(true);
        }
    }
}

function checkOneByOne(i, checkArr) {
    if( !checkArr || checkArr[i] == undefined) {
        setTimeout(checkCoupons, 100);
        return;
    }

    // if(!checkArr[i].aliDat || (parseFloat(checkArr[i].dbDat.zkPrice) < parseFloat(checkArr[i].aliDat.zk_final_price))) {
    //     goodsDao.deleteAuctionIdFromDb(checkArr[i].dbDat.auctionId, doNothing);
    //     goodsDao.deleteAuctionIdFromBoutiquePoll(checkArr[i].dbDat.auctionId, doNothing);
    //     if(checkArr[i].dbDat.source == 'HTK') {
    //         requestToPD([checkArr[i].dbDat.pdId], '商品价格有误,系统自动下架！');
    //     }
    //     setTimeout(function(){
    //         ++i;
    //         checkOneByOne(i, checkArr);
    //     } , 1000);
    //     return;
    // }

    // 旧的检查券
    // hidCouDao.expired(checkArr[i].dbDat.hiddenActivityId, checkArr[i].dbDat.sellerId, checkArr[i].dbDat.auctionId, function(e, couponInfo){
    //     // console.log(couponInfo);
    //     if(e) {
    //         console.log(e);
    //         if(e == '获取隐藏券失败') {
    //             console.log('try  again');
    //             setTimeout(function(){
    //             checkOneByOne(i, checkArr);
    //         } , checkGoodsInterval);
    //         return;
    //         } else {
    //         setTimeout(function(){
    //             ++i;
    //             checkOneByOne(i, checkArr);
    //         } , checkGoodsInterval);
    //         return;
    //         }
    //     }
    //     // if(!checkArr[i].aliDat || parseFloat(checkArr[i].dbDat.zkPrice) < parseFloat(checkArr[i].aliDat.zk_final_price) ) {
    //     //     goodsDao.deleteAuctionIdFromDb(checkArr[i].dbDat.auctionId, doNothing);
    //     //     goodsDao.deleteAuctionIdFromBoutiquePoll(checkArr[i].dbDat.auctionId, doNothing);
    //     //     if(checkArr[i].dbDat.source == 'HTK' && parseInt(checkArr[i].dbDat.pdId) != 0) {
    //     //         requestToPD([checkArr[i].dbDat.pdId], '商品价格有误,系统自动下架！');
    //     //     }
    //     // }
    //     // else 
    //     if(couponInfo.couponAmount == 0) {
    //         console.log('失效！');
    //         goodsDao.deleteByHiddenActivityIdFromDb(checkArr[i].dbDat.hiddenActivityId, doNothing);
    //         goodsDao.deleteByHiddenActivityIdFromBoutiquePoll(checkArr[i].dbDat.hiddenActivityId, doNothing);
    //         if(checkArr[i].dbDat.source == 'HTK' && parseInt(checkArr[i].dbDat.pdId) != 0) {
    //             requestToPD([checkArr[i].dbDat.pdId], '优惠券已失效,系统自动下架！');
    //         }
    //     }
    //     else{
    //         if(!checkArr[i].dbDat.hiddenEndTime){
    //             goodsDao.updateHiddenCoupon(couponInfo, function(err, data) {
    //                 if(err) {
    //                     console.log(err);
    //                 }
    //             });
    //         }
    //         goodsDao.updatebiz30daysAndPrice(checkArr[i].dbDat.auctionId, checkArr[i].aliDat.volume, checkArr[i].aliDat.zk_final_price, checkArr[i].aliDat.seller_id, checkArr[i].aliDat.nick, doNothing);
    //     }
    //     console.log('检查券');
    //     setTimeout(function(){
    //         ++i;
    //         checkOneByOne(i, checkArr);
    //     } , checkGoodsInterval);
    // });

    aliApiHelper.analysisCouponUrl({item_id: checkArr[i].dbDat.auctionId, activity_id: checkArr[i].dbDat.hiddenActivityId}, function(e, result) {
        if(e) {
            if(e.code == 15 ) {
                console.log('商品下架');
                goodsDao.deleteByHiddenActivityIdFromDb(checkArr[i].dbDat.hiddenActivityId, doNothing);
                goodsDao.deleteByHiddenActivityIdFromBoutiquePoll(checkArr[i].dbDat.hiddenActivityId, doNothing);
                if(checkArr[i].dbDat.source == 'HTK' && parseInt(checkArr[i].dbDat.pdId) != 0) {
                    requestToPD([checkArr[i].dbDat.pdId], '该商品已从淘宝店下架！');
                }
            } else {
                console.log(e);
                setTimeout(function(){
                    ++i;
                    checkOneByOne(i, checkArr);
                } , checkGoodsInterval);
                return;
            }
        }
        else if(result && result.data && result.data.coupon_total_count == 0 ) {
            var time = commonUtil.formatDate(new Date(), true);
            var t2 = new Date(checkArr[i].dbDat.hiddenStartTime).getTime();
            t2 = t2 + 1000*3600*14;
            if(new Date(checkArr[i].dbDat.hiddenStartTime).getTime() == new Date(time).getTime()) {
                console.log('检查券');
                   setTimeout(function(){
                    ++i;
                 checkOneByOne(i, checkArr);
                 } , checkGoodsInterval);
                 return;
            } else if(t2 < new Date().getTime()){
                console.log('失效！');
                goodsDao.deleteByHiddenActivityIdFromDb(checkArr[i].dbDat.hiddenActivityId, doNothing);
                goodsDao.deleteByHiddenActivityIdFromBoutiquePoll(checkArr[i].dbDat.hiddenActivityId, doNothing);
                if(checkArr[i].dbDat.source == 'HTK' && parseInt(checkArr[i].dbDat.pdId) != 0) {
                console.log(checkArr[i].dbDat.pdId);
                requestToPD([checkArr[i].dbDat.pdId], '优惠券已失效,系统自动下架！');
                }
            } else {
                console.log('检查券 ____');
                   setTimeout(function(){
                    ++i;
                 checkOneByOne(i, checkArr);
                 } , checkGoodsInterval);
                 return;
            }
        } else {
            goodsDao.updatebiz30daysAndPrice(checkArr[i].dbDat.auctionId, checkArr[i].aliDat.volume, checkArr[i].aliDat.zk_final_price, checkArr[i].aliDat.seller_id, checkArr[i].aliDat.nick, doNothing);
        }
        console.log('检查券');
        setTimeout(function(){
            ++i;
            checkOneByOne(i, checkArr);
        } , checkGoodsInterval);
    });
}

function checkCoupons() {
    bgTask.goodsIdFinishProcess = 0;
    goodsDao.read20GoodsToUpdate(bgTask.goodsIdFinishProcess, function (err, goodsList) {
        if (err || !goodsList) {
            console.log(err);
           setTimeout(checkCoupons, 100);
            return;
        }
        bgTask.onDoingGoodList = goodsList;
        if(bgTask.onDoingGoodList.length <= 0){
            bgTask.goodsIdFinishProcess = 0;
            setTimeout(checkCoupons, 100);
            return;
        }

        if(bgTask.onDoingGoodList.length > 0) {
            getGoodsInfoFromAlimama(bgTask.onDoingGoodList, function (err, result) {
                if (err) {
                    bgTask.goodsIdFinishProcess = 0;
                   setTimeout(checkCoupons, 100);
                    return;
                }
                bgTask.onDoingGoodListAli = result;
                var checkArr = [];
                for(var k in bgTask.onDoingGoodListAli){
                    checkArr.push(bgTask.onDoingGoodListAli[k]);
                }
                if(checkArr.length > 0) {
                    checkOneByOne(0, checkArr);
                } else {
                    setTimeout(checkCoupons, 100);
                    return;
                }
            });
        } else {
              setTimeout(checkCoupons, 100);
              return;
        }
    });
}
// function doCheckCoupons(checkArr) {
//     checkArr.forEach(function(g) {
//         hidCouDao.expired(g.dbDat.hiddenActivityId, g.dbDat.sellerId, g.dbDat.auctionId, function(e, couponInfo){
//             if(e) {
//                 console.log(e);
//                 return;
//             }
//             if(couponInfo.couponAmount == 0) {
//                 console.log('失效！');
//                 goodsDao.deleteByHiddenActivityIdFromDb(g.dbDat.hiddenActivityId, doNothing);
//                 goodsDao.deleteByHiddenActivityIdFromBoutiquePoll(g.dbDat.hiddenActivityId, doNothing);
//                 if(g.dbDat.source == 'HTK' && parseInt(g.dbDat.pdId) != 0) {
//                     requestToPD([g.dbDat.pdId], '优惠券已失效,系统自动下架！');
//                 }
//             }
//             else{
//                 if(!g.dbDat.hiddenEndTime){
//                     goodsDao.updateHiddenCoupon(couponInfo, function(err, data) {
//                         if(err) {
//                             console.log(err);
//                         }
//                     });
//                 }
//                 goodsDao.updatebiz30daysAndPrice(g.dbDat.auctionId, g.aliDat.volume, g.aliDat.zk_final_price, g.aliDat.seller_id, g.aliDat.nick, doNothing);
//             }
//             console.log('检查券');
//         });
//     });
// }
// function concurrentCheckCoupons() {
//     bgTask.goodsIdFinishProcess = 0;
//     goodsDao.read20GoodsToUpdate(bgTask.goodsIdFinishProcess, function (err, goodsList) {
//         if (err || !goodsList) {
//             console.log(err);
//             setTimeout(concurrentCheckCoupons, 100);
//             return;
//         }
//         bgTask.onDoingGoodList = goodsList;
//         if(bgTask.onDoingGoodList.length <= 0){
//             bgTask.goodsIdFinishProcess = 0;
//             setTimeout(concurrentCheckCoupons, 100);
//             return;
//         }

//         if(bgTask.onDoingGoodList.length > 0) {
//             getGoodsInfoFromAlimama(bgTask.onDoingGoodList, function (err, result) {
//                 if (err) {
//                     bgTask.goodsIdFinishProcess = 0;
//                     setTimeout(concurrentCheckCoupons, 100);
//                     return;
//                 }
//                 bgTask.onDoingGoodListAli = result;
//                 var checkArr = [];
//                 for(var k in bgTask.onDoingGoodListAli){
//                     checkArr.push(bgTask.onDoingGoodListAli[k]);
//                 }
//                 if(checkArr.length > 0) {
//                     doCheckCoupons(checkArr);
//                 } else {
//                     setTimeout(concurrentCheckCoupons, 100);
//                     return;
//                 }
//             });
//         } else {
//             setTimeout(concurrentCheckCoupons, 100);
//             return;
//         }
//     });
// }

function runOnce () {
    bgTask.jobTimerId = 0;
    // if(bgTask.gatherSource.indexOf('dataoke') >= 0){
    //     runOnceGatherDTK();
    // }
    // if(bgTask.gatherSource.indexOf('haodanku') >= 0){
    //     runOnceGatherHDK();
    // }
    runOnceExpire();
    // setSellerIdIfNull();
    // concurrentCheckCoupons();
    bgTask.jobTimerId = setTimeout(runOnce, 1000);
}

bgTask.start = function () {
    bgTask.isRunning = true;
    if(bgTask.jobTimerId) return;
    bgTask.goodsIdFinishProcess = 0;
    // if(!bgTask.gatherSource) bgTask.gatherSource = 'dataoke, haodanku';
    // if(!bgTask.gatherSource) bgTask.gatherSource = 'dataoke';
    // if(!bgTask.gatherSource) bgTask.gatherSource = 'haodanku';
    // checkCoupons();
    // runOnceExpire();
    runOnce();
}

bgTask.stop = function () {
    bgTask.isRunning = false;
    if(!bgTask.jobTimerId) return;
    clearTimeout(bgTask.jobTimerId);
    clearTimeout(runOnce);
    bgTask.jobTimerId = 0;
}
